package com.atguigu.spzx.common.exception.intercepter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.exception.SPZXException;
import com.atguigu.spzx.common.util.AuthContextUtil;
import com.atguigu.spzx.model.entity.user.UserInfo;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;



public class UserLoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(StrUtil.isEmpty(token)){
            throw new SPZXException(ResultCodeEnum.LOGIN_AUTH);
        }
        String userInfo = redisTemplate.opsForValue().get("user:login:" + token);
        AuthContextUtil.set(JSON.parseObject(userInfo, UserInfo.class));
        return true;
    }

}
